import { useProducts } from "@/hooks/use_products";
import { useProductsStore } from "@/hooks/use_products_store";
import { ActionIcon, Box, Flex, Paper, Text, TextInput, Title, Tooltip } from "@mantine/core";
import { IconDeselect, IconListCheck, IconSearch, IconX } from "@tabler/icons-react";
import { isEmpty, not } from "ramda";
import { useCallback, useMemo, useState } from "react";
import classes from "./ProductList.module.css";

export function ProductList() {
  const [keyword, setKeyword] = useState<string>("");
  const [selected, products, selectAll, unselectAll] = useProductsStore((state) => [
    state.selectedProducts,
    state.products,
    state.selectAll,
    state.unselectAll,
  ]);
  const clearSearchKeyword = useCallback(() => setKeyword(""), []);
  useProducts(keyword);

  return (
    <Paper shadow="md" p="lg" h="100%">
      <Flex direction="column" justify="flex-start" align="stretch" gap="md" h="100%">
        <Flex direction="row" justify={"space-between"} align={"center"} gap="sm">
          <Title order={4} className={classes["title"]} maw={650}>
            产品列表{not(isEmpty(selected)) && `（已选择 ${selected.length} 个产品）`}
          </Title>
          <Tooltip label="取消当前的所有选择">
            <ActionIcon size="lg" color="red" onClick={unselectAll} disabled={isEmpty(selected)}>
              <IconDeselect size={16} />
            </ActionIcon>
          </Tooltip>
          <Tooltip label="选择当前所有">
            <ActionIcon size="lg" onClick={selectAll}>
              <IconListCheck size={16} />
            </ActionIcon>
          </Tooltip>
          <TextInput
            placeholder="输入关键词检索产品"
            className={classes["title-search"]}
            value={keyword}
            onChange={(event) => setKeyword(event.currentTarget.value)}
            leftSection={<IconSearch size={16} />}
            rightSection={
              <ActionIcon
                variant="transparent"
                color="gray"
                onClick={clearSearchKeyword}
                disabled={isEmpty(keyword)}
              >
                <IconX size={16} />
              </ActionIcon>
            }
          />
        </Flex>
        <Flex
          direction="row"
          justify="flex-start"
          align="flex-start"
          wrap="wrap"
          gap="sm"
          className={classes["product-list-container"]}
        >
          {products.map((product) => (
            <ProductItem key={product.id} id={product.id} name={product.name} />
          ))}
        </Flex>
      </Flex>
    </Paper>
  );
}

interface ProductItemProps {
  id: string;
  name: string;
}

function ProductItem(props: ProductItemProps) {
  const [selectedProducts, append, remove] = useProductsStore((state) => [
    state.selectedProducts,
    state.append,
    state.remove,
  ]);
  const selected = useMemo(() => selectedProducts.includes(props.id), [props.id, selectedProducts]);

  const handleSelectAction = useCallback(() => {
    if (selected) {
      remove(props.id);
    } else {
      append(props.id);
    }
  }, [props.id, selected, append, remove]);

  return (
    <Box
      px="sm"
      py="xs"
      bg={selected ? "green" : "gray"}
      className={classes["product-item"]}
      onClick={handleSelectAction}
    >
      <Text size="xs" c={selected ? "white" : "gray"}>
        {props.name}
      </Text>
    </Box>
  );
}
